﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Data;
using JXT.PrimaryKey.Batman.Extensions;
using JXT.PrimaryKey.Batman.Domain.Models;
using JXT.PrimaryKey.Batman.Domain.Specifications;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Models;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Repositories;
using JXT.PrimaryKey.Batman.Domain.Repositories.SqlServer.Expressions;

namespace JXT.PrimaryKey.Batman.Domain.Repositories.SqlServer.UserSystem
{
    public class SqlRoleRepository : SqlServerRepositoryBase<Role, int>, IRoleRepository
    {
        public SqlRoleRepository(RepositoryContext context)
            : base((SqlServerRepositoryContext)context)
        {
        }

        public override void Add(Role entity)
        {
            //base.Add(entity);
            string sql = "insert into [role]([name],[summary],[issystem],[authority]) values(@name,@summary,@issystem,@authority);select @@identity;";
            List<IDataParameter> parameterList = new List<IDataParameter>();
            parameterList.Add(Context.CreateParameter("@name", entity.Name));
            parameterList.Add(Context.CreateParameter("@summary", entity.Summary));
            parameterList.Add(Context.CreateParameter("@issystem", entity.IsSystem));
            parameterList.Add(Context.CreateParameter("@authority", entity.Authorities.ToJsonString()));
            entity.Id=Convert.ToInt32(Context.ExecuteScalar(sql,parameterList.ToArray()));
        }

        public override void Update(Role entity)
        {
            //base.Update(entity);
            string sql = "update [role] set [name]=@name,[summary]=@summary,[issystem]=@issystem,[authority]=@authority where [id]=@id";
            List<IDataParameter> parameterList = new List<IDataParameter>();
            parameterList.Add(Context.CreateParameter("@name", entity.Name));
            parameterList.Add(Context.CreateParameter("@summary", entity.Summary));
            parameterList.Add(Context.CreateParameter("@issystem", entity.IsSystem));
            parameterList.Add(Context.CreateParameter("@authority", entity.Authorities.ToJsonString()));
            parameterList.Add(Context.CreateParameter("@id",entity.Id));
            Context.ExecuteNonQuery(sql,parameterList.ToArray());
        }

        protected override Role ReadEntityFromDataReader(IDataReader dr)
        {
            Role role = new Role()
            {
                Id = dr.Read<int>("id"),
                IsSystem = dr.Read<bool>("issystem"),
                Summary = dr.Read<string>("summary"),
                Name = dr.Read<string>("name"),
                Authorities = dr.Read<string>("authority").ToJsonObject<Authority[]>()
            };
            return role;
        }
    }
}
